package com.leaf.spring_five.jms;

import java.util.Map;

import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.MessagePostProcessor;

import com.google.common.collect.Maps;

/**
 * 使用MessageCreator回调接口从提供的会话对象中创建一个文本消息，并且通过一个ConnectionFactory的引用来构造JmsTemplate
 */
public class JmsQueueSender {

	private JmsTemplate jmsTemplate;
	
	private Queue queue;
	
	public void setConnectionFactory(ConnectionFactory cf){
		this.jmsTemplate = new JmsTemplate(cf);
	}
	
	public void setQueue(Queue queue){
		this.queue = queue;
	}
	
	/**
	 * 简单消息发送
	 */
	public void simpleSend(){
		this.jmsTemplate.send(this.queue, new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage("hello queue world");
			}
		});
	}
	
	/**
	 * 使用消息转换器
	 */
	public void sendWithConversion(){
		Map<String, Object> map = Maps.newHashMap();
		map.put("Name", "Mark");
		map.put("Age", new Integer(47));
		
		this.jmsTemplate.convertAndSend("testQueue", map, new MessagePostProcessor() {
			
			@Override
			public Message postProcessMessage(Message message) throws JMSException {
				message.setIntProperty("AccountID", 888888);
				message.setJMSCorrelationID("666666");
				return message;
			}
		});
		/**
		 * 产生的消息格式：
		 * MapMessage={
				Header={
					... standard headers ...
					CorrelationID={666666}
				}
				Properties={
					AccountID={Integer:888888}
				}
				Fields={
					Name={String:Mark}
					Age={Integer:47}
				}
			}
		 */
	}
	
}
